<template>
    <div>
        <div class="i-layout-page-header">
            <PageHeader class="product_tabs" hidden-breadcrumb>
                <div slot="title">
                <router-link :to="{ path: '/admin/marketing/feedback/disposition' }"
                    ><Button icon="ios-arrow-back" size="small" class="mr20"
                    >返回</Button
                    ></router-link
                >
                <span
                    v-text="$route.params.id ? '编辑问卷' : '添加问卷'"
                    class="mr20"
                ></span>
                </div>
            </PageHeader>
        </div>
        <div class="survey-header">
            <div>
                <Input v-model="surveyTitle" placeholder="请输入问卷标题" style="width:300px;margin-right:20px"/>
                <i-switch
                v-model="surveyStatus"
                :value="surveyStatus"
                :true-value="1"
                :false-value="0"
                size="large"
                >
                <span slot="open">上架</span>
                <span slot="close">下架</span>
                </i-switch>
            </div>
           <div class="wenbenk">
                <Input v-model="top_desc" type="textarea" placeholder="请输入顶部描述" style="width:300px;margin-right:20px"/>
                <Input v-model="bottom_desc" type="textarea" placeholder="请输入底部描述" style="width:300px;margin-right:20px"/>
                <p></p>
           </div>
        </div>
        <RadioGroup v-model="selectedFrequency" style="margin-top: -6px;">
            <Radio :label="1">小题</Radio>
            <Radio :label="2">大题</Radio>
        </RadioGroup>
        <div v-if="selectedFrequency === 1" class="question-form">
            <h3>小题设置</h3>
            <Form :model="questionForm" :label-width="100">
                <FormItem label="题目类型：">
                    <RadioGroup v-model="questionForm.question_type" style="margin-top: -20px;">
                        <Radio label="radio">单选</Radio>
                        <Radio label="checkbox">多选</Radio>
                        <Radio label="text">文本</Radio>
                        <Radio label="rating">评分</Radio>
                        <Radio label="time">时间</Radio>
                        <Radio label="Information">基本信息</Radio>
                        <Radio label="image">图片</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="题目标题：">
                    <Input style="width: 380px" v-model="questionForm.question_text" placeholder="请输入题目标题" />
                </FormItem>
                <FormItem label="是否必填：">
                    <i-switch
                        v-model="questionForm.is_required"
                        :true-value="1"
                        :false-value="0"
                    >
                        <span slot="open">必填</span>
                        <span slot="close">选填</span>
                    </i-switch>
                </FormItem>
                <!-- 选项输入区域 -->
                <FormItem v-if="questionForm.question_type === 'radio' || questionForm.question_type === 'checkbox'">
                    <div class="options-area">
                        <Input 
                            v-for="(option, index) in questionForm.question_options" 
                            v-model="questionForm.question_options[index]"
                            :key="index"
                            :placeholder="`选项 ${index + 1}`"
                            style="width:200px;margin:5px"
                        />
                        <Button type="dashed" @click="addOption" style="margin:5px">添加选项</Button>
                    </div>
                </FormItem>
                <!-- 评分范围设置 -->
                <FormItem v-if="questionForm.question_type === 'rating'">
                    <div class="options-area">
                        <InputNumber v-model="questionForm.min" placeholder="最低分" style="width:100px;margin-right:10px"/>
                        <InputNumber v-model="questionForm.max" placeholder="最高分" style="width:100px"/>
                    </div>
                </FormItem>
                <FormItem>
                    <Button v-if="isEditing" type="primary" @click="saveQuestion">确认修改</Button>
                    <Button v-else type="primary" @click="addQuestionOrBigQuestion('question')">确认添加</Button>
                </FormItem>
            </Form>
        </div>
        <div v-if="selectedFrequency === 2" class="question-form">
            <h3>大题设置</h3>
            <Form :model="bigQuestionForm" :label-width="100">
                <FormItem label="大题标题：">
                    <Input v-model="bigQuestionForm.question_text" placeholder="请输入大题标题" />
                </FormItem>
                <FormItem>
                    <Button v-if="isEditing" type="primary" @click="saveBigQuestion">确认修改</Button>
                    <Button v-else type="primary" @click="addQuestionOrBigQuestion('header')" :disabled="!bigQuestionForm.question_text || bigQuestionForm.question.length === 0">确认添加</Button>
                </FormItem>
            </Form>
            <div class="sub-question-form">
                <h4>小题设置</h4>
                <Form :model="subQuestionForm" :label-width="100">
                    <FormItem label="题目类型：">
                        <RadioGroup v-model="subQuestionForm.question_type">
                            <Radio label="radio">单选</Radio>
                            <Radio label="checkbox">多选</Radio>
                            <Radio label="text">文本</Radio>
                            <Radio label="rating">评分</Radio>
                            <Radio label="time">时间</Radio>
                            <Radio label="Information">基本信息</Radio>
                            <Radio label="image">图片</Radio>
                        </RadioGroup>
                    </FormItem>
                    <FormItem label="题目标题：">
                        <Input v-model="subQuestionForm.question_text" placeholder="请输入题目标题" />
                    </FormItem>
                    <FormItem label="是否必填：">
                        <i-switch
                            v-model="subQuestionForm.is_required"
                            :true-value="1"
                            :false-value="0"
                        >
                            <span slot="open">必填</span>
                            <span slot="close">选填</span>
                        </i-switch>
                    </FormItem>
                    <FormItem v-if="subQuestionForm.question_type === 'radio' || subQuestionForm.question_type === 'checkbox'">
                        <div class="options-area">
                            <Input 
                                v-for="(option, index) in subQuestionForm.question_options" 
                                v-model="subQuestionForm.question_options[index]"
                                :key="index"
                                :placeholder="`选项 ${index + 1}`"
                                style="width:200px;margin:5px"
                            />
                            <Button type="dashed" @click="addSubOption" style="margin:5px">添加选项</Button>
                        </div>
                    </FormItem>
                    <FormItem v-if="subQuestionForm.question_type === 'rating'">
                        <div class="options-area">
                            <InputNumber v-model="subQuestionForm.min" placeholder="最低分" style="width:100px;margin-right:10px"/>
                            <InputNumber v-model="subQuestionForm.max" placeholder="最高分" style="width:100px"/>
                        </div>
                    </FormItem>
                    <FormItem>
                        <Button type="primary" @click="addSubQuestion">{{ editingSubIndex !== null ? '确认修改' : '添加小题' }}</Button>
                    </FormItem>
                </Form>
            </div>
            <div class="sub-question-list">
                <draggable v-model="bigQuestionForm.question" @end="onSubQuestionDragEnd">
                    <div v-for="(question, index) in bigQuestionForm.question" :key="index" class="question-item">
                        <span>{{ question.question_text }} ({{ question.question_type }})</span>
                        <Button type="primary" size="small" @click="editSubQuestion(index)" style="margin-left:10px">编辑</Button>
                        <Button type="error" size="small" @click="removeSubQuestion(index)" style="margin-left:10px">删除</Button>
                    </div>
                </draggable>
            </div>
        </div>
        <!-- 问题列表 -->
        <div class="question-list">
            <draggable v-model="combinedQuestions" @end="onDragEnd">
                <div v-for="(item, index) in combinedQuestions" :key="index" class="question-item">
                    <template v-if="item.question_type == 'header'">
                        <div class="big-question">
                            <div class="big-question-header">
                                <span>{{ item.question_text }} (大题)</span>
                                <Button type="primary" size="small" @click="editBigQuestion(index)" style="margin-left:10px">编辑</Button>
                                <Button type="error" size="small" @click="removeBigQuestion(index)" style="margin-left:10px">删除</Button>
                            </div>
                            <div class="sub-question-list">
                                <div v-for="(subQuestion, subIndex) in item.questions" :key="'sub-' + subIndex" class="sub-question-item">
                                    <span>{{ subQuestion.question_text }} ({{ subQuestion.question_type }})</span>
                                </div>
                            </div>
                        </div>
                    </template>
                    <template v-else>
                        <div class="single-question">
                            <span>{{ item.question_text }} ({{ item.question_type }})</span>
                            <Button type="primary" size="small" @click="editQuestion(index)" style="margin-left:10px">编辑</Button>
                            <Button type="error" size="small" @click="removeQuestion(index)" style="margin-left:10px">删除</Button>
                        </div>
                    </template>
                    
                </div>
            </draggable>
        </div>
        <Button type="primary" @click="submitSurvey" style="margin-top: 20px;">提交问卷</Button>
    </div>
</template>

<script>
import draggable from 'vuedraggable'
import { surveyAdd,surveyEdit,surveyDetail } from "@/api/marketing"; 
import { max } from 'moment';
import uploadPictures from "@/components/uploadPictures";
export default {
    components: {
        draggable
    },
    data() {
        return {
            surveyTitle:'',
            top_desc:'',
            bottom_desc:'',
            bg_image:"",
            surveyStatus:0,
            surveyId:this.$route.params.id,
            surveyDetail:{},
            selectedFrequency: 1,
            questionForm: {
                question_type: 'radio',
                question_text: '',
                is_required: 1,
                question_options: ['', ''],
                min: 1,
                max: 5
            },
            questions: [], // 添加questions数组
            isEditing: false,
            editingIndex: null,
            bigQuestionForm: {
                question_text: '',
                question: []
            },
            bigQuestions: [],
            subQuestionForm: {
                question_type: 'radio',
                question_text: '', 
                is_required: 1,
                question_options: ['', ''],
                min: 1,
                max: 5
            },
            editingSubIndex:null,
            allQuestions: [],
            itemId:"",
            // combinedQuestions: [], // 合并后的问题数组
        }
    },
    watch: {
        selectedFrequency(newVal) {
            if (newVal === 1) {
                this.resetForm()
            } else if (newVal === 2) {
                this.resetBigQuestionForm()
            }
        }
    },
    computed: {
        combinedQuestions: {
            get() {
                return this.allQuestions.sort((a, b) => a.createdAt - b.createdAt)
            },
            set(value) {
                this.allQuestions = value
            }
        }
    },
    created(){
        if (this.$route.params.id) {
            this.itemId = this.$route.params.id
            this.getSurveyDetail();
        }
    },
    methods: {
        // 编辑反显
        getSurveyDetail () {
            surveyDetail(this.$route.params.id).then(res => {
                this.surveyTitle = res.data.title
                this.top_desc = res.data.top_desc
                this.bottom_desc = res.data.bottom_desc
                this.bg_image = res.data.bg_image
                this.surveyStatus = res.data.is_show
                // this.combinedQuestions = res.data.question
                let arrList = res.data.question
                for(let i=0; i<arrList.length; i++){
                    if(arrList[i].question_type =='header'){
                        for(let a=0; a<arrList[i].question.length; a++){
                            if(arrList[i].question[a].question_type != 'rating'){
                                arrList[i].question[a].question_options = Object.values(arrList[i].question[a].question_options);
                                
                            }else{
                                arrList[i].question[a].max = Number(arrList[i].question[a].question_options.max)
                                arrList[i].question[a].min = Number(arrList[i].question[a].question_options.min)
                                arrList[i].question[a].question_options = []
                            }
                        }
                    }else{
                        // arrList[i].editing = false
                        if(arrList[i].question_type != 'rating'){
                            arrList[i].question_options = Object.values(arrList[i].question_options);
                            
                        }else{
                            arrList[i].max = Number(arrList[i].question_options.max)
                            arrList[i].min = Number(arrList[i].question_options.min)
                            arrList[i].question_options = []
                        }
                    }
                    
                }
                this.combinedQuestions = arrList
                console.log(this.combinedQuestions,"反显数组")
            }).catch(err => {
                this.$Message.error(err.msg);
            });
        },
        addOption() {
            this.questionForm.question_options.push('')
        },
        addQuestionOrBigQuestion(type) {
            if (type == 'question') {
                if (!this.questionForm.question_text) {
                    this.$Message.error('请填写题目标题')
                    return
                }
                // console.log(this.questionForm,this.questionForm.question_type,"123")
                this.allQuestions.push({
                    ...this.questionForm,
                    question_options: [...this.questionForm.question_options],
                    question_type: this.questionForm.question_type
                })
                console.log(this.allQuestions,"123")
                this.resetForm()
                this.isEditing = false // 确保在添加时重置编辑状态
                this.$Message.success('问题添加成功')
            } else if (type == 'header') {
               
                if (!this.bigQuestionForm.question_text) {
                    this.$Message.error('请填写大题标题')
                    return
                }
                if (this.bigQuestionForm.question.length === 0) {
                    this.$Message.error('请至少添加一个小题')
                    return
                }
                this.allQuestions.push({
                    ...this.bigQuestionForm,
                    question_type: 'header'
                })
                this.resetBigQuestionForm()
                this.isEditing = false // 确保在添加时重置编辑状态
                this.$Message.success('大题添加成功')
            }
            //  console.log(this.combinedQuestions,'22222')
        },
        saveBigQuestion() {
            if (!this.bigQuestionForm.question_text) {
                this.$Message.error('请填写大题标题');
                return;
            }
            if (this.bigQuestionForm.question.length === 0) {
                this.$Message.error('请至少添加一个小题');
                return;
            }
            // 修改逻辑
            this.$set(this.allQuestions, this.editingIndex, {
                ...this.bigQuestionForm,
                question_type: 'header'
            });
            this.combinedQuestions[this.editingIndex] = this.allQuestions[0]
            console.log(this.combinedQuestions[this.editingIndex],"修改大题")
            this.resetBigQuestionForm();
            this.resetBigQuestionForm();
            this.isEditing = false;
            this.editingIndex = null;
            this.$Message.success('大题修改成功');
        },
        // 修改原有的添加方法调用
        // saveQuestion() {
        //     if (!this.questionForm.question_text) {
        //         this.$Message.error('请填写题目标题')
        //         return
        //     }
        //     this.addQuestionOrBigQuestion('question')
        // },
        saveQuestion() {
            console.log(this.allQuestions,"小题确认修改")
            if (!this.questionForm.question_text) {
                this.$Message.error('请填写题目标题')
                return
            }
            // 修改逻辑
            this.$set(this.allQuestions, this.editingIndex, {
                ...this.questionForm,
                question_options: [...this.questionForm.question_options],
                question_type: this.questionForm.question_type
            })
            this.resetForm()
            this.isEditing = false
            this.editingIndex = null
            this.$Message.success('问题修改成功')
        },
        addBigQuestion() {
            this.addQuestionOrBigQuestion('header')
        },
        editQuestion(index) {
            if(this.selectedFrequency == 2 || !this.selectedFrequency){
                this.selectedFrequency = 1
            }
            const question = this.allQuestions[index]
            console.log(question.question_type,"123456789")
            // if (!question || question.question_type !== 'question') {
            //     this.$Message.error('无法找到要编辑的小题')
            //     return
            // }
            this.questionForm = {
                question_text: question.question_text,
                question_type: question.question_type,
                question_options: question.question_options || [],
                min: question.min,
                max: question.max,
                is_required: question.is_required
            }
            this.isEditing = true
            this.editingIndex = index
            this.$forceUpdate() // 强制更新视图
        },
        editBigQuestion(index) {
            console.log(this.combinedQuestions[index], "大题编辑")
            if (this.selectedFrequency == 1 || !this.selectedFrequency) {
                this.selectedFrequency = 2
            } else {
                const combinedQuestion = this.combinedQuestions[index]
                if (!combinedQuestion || combinedQuestion.question_type !== 'header') {
                    this.$Message.error('无法找到要编辑的大题')
                    return
                }
                // 直接使用 combinedQuestions 数组中的索引
                this.bigQuestionForm = JSON.parse(JSON.stringify(combinedQuestion)) // 使用深拷贝确保数据独立
                this.isEditing = true
                this.editingIndex = index // 直接使用传入的索引
                this.$forceUpdate() // 强制更新视图
            }
        },
        
        
        resetForm() {
            this.questionForm = {
                question_type: 'radio',
                question_text: '',
                is_required: 0,
                question_options: ['', ''],
                min: 1,
                max: 5
            }
        },
        addBigQuestion() {
            if (!this.bigQuestionForm.question_text) {
                this.$Message.error('请填写大题标题')
                return
            }
            if (this.bigQuestionForm.question.length === 0) {
                this.$Message.error('请至少添加一个小题')
                return
            }
            if (this.isEditing) {
                this.$set(this.bigQuestions, this.editingIndex, {
                    ...this.bigQuestionForm
                })
                this.isEditing = false
                this.editingIndex = null
                this.$Message.success('大题修改成功')
            } else {
                this.bigQuestions.push({
                    ...this.bigQuestionForm
                })
                this.$Message.success('大题添加成功')
            }
            this.resetBigQuestionForm()
        },
        
        removeSubQuestion(index) {
            this.bigQuestionForm.question.splice(index, 1)
            this.$Message.success('小题删除成功')
        },
        resetBigQuestionForm() {
            this.bigQuestionForm = {
                question_text: '',
                question: []
            }
        },
        addSubOption() {
            this.subQuestionForm.question_options.push('')
        },
        addSubQuestion() {
            console.log(this.editingSubIndex,"123468")
            if (!this.subQuestionForm.question_text) {
                this.$Message.error('请填写题目标题')
                return
            }
            if (this.editingSubIndex !== null) {
                this.bigQuestionForm.question.splice(this.editingSubIndex, 1, {
                    ...this.subQuestionForm,
                    question_options: [...this.subQuestionForm.question_options]
                })
                this.editingSubIndex = null
                this.$Message.success('小题修改成功')
            } else {
                console.log(this.bigQuestionForm,"12346899")
                this.bigQuestionForm.question.push({
                    ...this.subQuestionForm,
                    question_options: [...this.subQuestionForm.question_options]
                })
                
                this.$Message.success('小题添加成功')
            }
            this.resetSubQuestionForm()
            this.$forceUpdate() // 强制更新视图
        },
        resetSubQuestionForm() {
            this.subQuestionForm = {
                question_type: 'radio',
                question_text: '',
                is_required: 1,
                question_options: ['', ''],
                min: 1,
                max: 5
            }
        },
        removeBigQuestion(index) {
            const combinedQuestion = this.combinedQuestions[index]
            if (!combinedQuestion || combinedQuestion.question_type !== 'header') {
                this.$Message.error('无法找到要删除的大题')
                return
            }
            this.allQuestions.splice(index, 1)
            this.$Message.success('大题删除成功')
        },
        onDragEnd() {
            console.log(this.combinedQuestions,"123456789")
            this.$Message.success('问题顺序已更新')
        },
        onSubQuestionDragEnd() {
            console.log(this.bigQuestionForm.question,"123456789")
            // 更新大题中的小题顺序
            this.$Message.success('小题顺序已更新')
        },
        editSubQuestion(index) {
            // 获取当前小题数据
            const subQuestion = this.bigQuestionForm.question[index];
            // 将数据填充到小题表单
            this.subQuestionForm = {
                question_text: subQuestion.question_text,
                question_type: subQuestion.question_type, // 修复：使用 question_type 而不是 type
                question_options: subQuestion.question_options || [],
                min: subQuestion.min,
                max: subQuestion.max,
                is_required: subQuestion.is_required
            };
            // 设置当前编辑的小题索引
            this.editingSubIndex = index; // 修复：使用 editingSubIndex 而不是 currentEditIndex
            this.$forceUpdate(); // 强制更新视图
        },
        removeQuestion(index) {
            const question = this.allQuestions[index]
            if (!question) {
                this.$Message.error('无法找到要删除的小题')
                return
            }
            this.allQuestions.splice(index, 1)
            this.$Message.success('小题删除成功')
        },
        // submitSurvey() {
        //     const surveyData = {
        //         title: this.surveyTitle,
        //         topDesc: this.top_desc,
        //         bottomDesc: this.bottom_desc,
        //         status: this.surveyStatus,
        //         questions: this.combinedQuestions
        //     };
        //     console.log('提交的问卷数据：', surveyData);
        //     this.$Message.success('问卷数据已提交');
        //     // 这里可以添加实际的提交逻辑，如调用API等
        // },
        submitSurvey() {
            if(this.itemId>0 && this.itemId){
                surveyEdit(this.itemId,{
                    title: this.surveyTitle,
                    top_desc: this.top_desc,
                    bottom_desc: this.bottom_desc,
                    bg_image: this.bg_image,
                    description:"",
                    is_show: this.surveyStatus,
                    questions: this.combinedQuestions
                })
                .then(async (res) => {
                    this.$Message.success(res.msg);
                    setTimeout(() => {
                        this.$router.push({
                            path: "/admin/marketing/feedback/disposition",
                        });
                    }, 500);
                })
                .catch((res) => {
                    this.$Message.error(res.msg);
                });
            }else{
                surveyAdd({
                    title: this.surveyTitle,
                    bottom_desc: this.bottom_desc,
                    top_desc: this.top_desc,
                    bg_image: this.bg_image,
                    description:"",
                    is_show: this.surveyStatus,
                    questions: this.combinedQuestions
                })
                .then(async (res) => {
                    this.$Message.success(res.msg);
                    setTimeout(() => {
                        this.$router.push({
                            path: "/admin/marketing/feedback/disposition",
                        });
                    }, 500);
                })
                .catch((res) => {
                    this.$Message.error(res.msg);
                });
            }
        }
    }
    
}
</script>

<style scoped lang="stylus">
.i-layout-page-header {
    background: #fff;
    // padding: 20px;
    margin-bottom: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.product_tabs {
    .mr20 {
        margin-right: 20px;
    }
}

.survey-header {
    .ivu-switch {
        margin-left: 20px;
        margin-top: -16px;
    }
    .wenbenk{
        display: flex;
        align-items: center;
        margin-top: 0px;
    }
}

.ivu-radio-group {
    margin-top: 20px;
    padding: 20px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    
    .ivu-radio-wrapper {
        margin-right: 20px;
        font-size: 14px;
    }
}

.ivu-input-wrapper {
    margin-bottom: 20px;
    
    &:last-child {
        margin-bottom: 0;
    }
}
.question-form {
    margin-top: 20px;
    padding: 20px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    
    h3 {
        margin-bottom: 20px;
        font-size: 16px;
        color: #333;
    }
}
.options-area {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}
.question-list {
    margin-top: 20px;
}

.question-item {
    padding: 10px;
    margin-bottom: 10px;
    background: #f5f5f5;
    border-radius: 4px;
    display: flex;
    align-items: center;
}
</style>

<style scoped>
.big-question {
    margin-bottom: 20px;
    padding: 15px;
    border: 1px solid #e8eaec;
    border-radius: 4px;
}

.big-question-header {
    margin-bottom: 10px;
}

.sub-question-list {
    margin-left: 20px;
}

.sub-question-item {
    margin: 5px 0;
    padding: 5px;
    background-color: #f8f8f9;
    border-radius: 4px;
}

.single-question {
    margin: 10px 0;
    padding: 10px;
    background-color: #f8f8f9;
    border-radius: 4px;
}
</style>
  